import { Button, App, Input, Form } from 'antd'
import React, { useEffect, useState } from 'react'
import { CheckCircleOutlined, CopyOutlined, LinkOutlined, UploadOutlined } from '@ant-design/icons'
import './Notarization.less'
import { useModel } from '@umijs/max'
import { copyLink } from '@/utils/utils'

const TextArea = Input.TextArea

const Notarization = ({ order_id }) => {
  const {
    GetApiToken,
    PushCustomerInfo,
    PushIdCardInfo,
    ReadyNotary,
    PushContractInfo,
    QueryNotary,
    CancelNotary,
    GetNotaryLink,
    QueryNotaryCount
  } = useModel('BillingDetails')

  const { setIsLoading } = useModel('Global')

  const { message, modal } = App.useApp()
  const [orderInfoFormRef] = Form.useForm()

  const [baseParams, setBaseParams] = useState({}) // 基础传参

  // 处理公证信息上报
  const handleOrderInfo = () => {
    modal.confirm({
      width: 600,
      icon: <UploadOutlined />,
      title: '上传公证信息',
      content: (
        <div className='order_content'>
          <Form preserve={false} form={orderInfoFormRef} layout='vertical' name='order_info'>
            <Form.Item name='address' label='户籍地址 : ' rules={[{ required: true, message: '请输入户籍地址' }]}>
              <TextArea showCount maxLength={200} placeholder='请输入户籍地址' allowClear />
            </Form.Item>
          </Form>
        </div>
      ),
      onOk: async () => {
        await orderInfoFormRef.validateFields()
        const { address } = orderInfoFormRef.getFieldsValue()
        let params = {
          ...baseParams,
          address
        }
        const res = await PushCustomerInfo(params)
        if (res) {
          // 用户身份
          const userIdentity = await PushIdCardInfo(params)
          if (userIdentity) {
            // 合同信息
            const contractInfo = await PushContractInfo(params)
            if (contractInfo) {
              // 弹窗展示合同链接
              modal.info({
                title: '合同链接',
                content: (
                  <a target='_blank' href={contractInfo} rel='noreferrer'>
                    <LinkOutlined /> 公证合同,请下载后务必妥善保管{' '}
                  </a>
                )
              })
            }
          }
        }
      }
    })
  }

  const handleCopyLink = ({ link }) => {
    copyLink(link)
  }

  // 处理申请公证链接
  const handleNotarizationLink = async type => {
    setIsLoading(true)
    let res = type === 'application' ? await ReadyNotary(baseParams) : await GetNotaryLink(baseParams)
    let title = type === 'application' ? '申请公证' : '更新公证链接'

    if (res) {
      modal.info({
        width: 700,
        title,
        icon: <LinkOutlined />,
        okText: '关闭',
        content: <ApplicationNotarizationContent res={res} />
      })
    }
    setIsLoading(false)
  }

  // 链接组件
  const CopyAndUploadLink = link => {
    return (
      <Button size={'small'} type='primary' style={{ marginLeft: '5px' }} onClick={() => handleCopyLink(link)}>
        <CopyOutlined />
        复制链接
      </Button>
    )
  }

  // 处理申请公证内容组件
  const ApplicationNotarizationContent = ({ res }) => {
    let { weiXinHttpUrl, weiXinSchemaUrl } = res
    return (
      <div>
        <div className='application_tips'>链接有效期为5分钟,请尽快使用,如过期请点击更新链接进行重新获取</div>
        <div className='application_content'>
          <div>
            <p>1. 可以在任意地方打开该链接，进行公证</p>
            <Input
              value={weiXinHttpUrl}
              disabled
              style={{ width: '100%' }}
              suffix={<CopyAndUploadLink link={weiXinHttpUrl} />}
            />
          </div>

          <div>
            <p>2. 只能在微信中打开该链接，进行公证</p>
            <Input
              value={weiXinSchemaUrl}
              disabled
              style={{ width: '100%' }}
              suffix={<CopyAndUploadLink link={weiXinSchemaUrl} />}
            />
          </div>
        </div>
      </div>
    )
  }

  // 处理取消公证
  const handleCancelNotarization = () => {
    modal.confirm({
      title: '取消公证',
      content: '确定取消公证吗？',
      onOk: async () => {
        const res = await CancelNotary(baseParams)
        if (res) {
          message.success('取消公证成功')
        }
      }
    })
  }

  // 处理查询公证结果
  const handleQueryNotarization = async () => {
    const res = await QueryNotary(baseParams)
    if (res) {
      modal.info({
        title: '查询公证结果',
        icon: <CheckCircleOutlined />,
        content: (
          <div className='notarization_result'>
            {res.map(item => {
              return (
                <>
                  <p className='application_tips'>{item.name}</p>
                  {item.fileType === 'video' ? (
                    <video width='300' height='240' controls src={item.fileURL} />
                  ) : (
                    <a target='_blank' href={item.fileURL} rel='noreferrer'>
                      <LinkOutlined />
                      {item.certificateNO}
                    </a>
                  )}
                </>
              )
            })}
          </div>
        )
      })
    }
  }

  // 前置获取 token
  const handleGetToken = async () => {
    const token = await GetApiToken()
    if (token) {
      setBaseParams({
        token,
        order_id
      })
    }
  }

  // 处理更新身份信息
  const handleUpdateIdCard = async () => {
    modal.confirm({
      title: '更新身份信息',
      content: '确定更新身份信息吗？',
      onOk: async () => {
        const res = await PushIdCardInfo(baseParams)
        if (res) {
          message.success('更新身份信息成功')
        }
      }
    })
  }

  // 处理查看已出证数量
  const handleQueryNotarizationCount = async () => {
    const res = await QueryNotaryCount(baseParams)
    if (res) {
      modal.info({
        title: '已出证数量',
        content: (
          <div className='notarization_count'>
            <p>已出证数量: {res}</p>
          </div>
        )
      })
    }
  }

  useEffect(() => {
    handleGetToken()
  }, [])

  // 公证按钮组
  const notarizationBtnList = [
    {
      key: 'order_info',
      name: '上传公证信息',
      bgColor: '#FFECE8',
      color: '#F53F3F',
      method: handleOrderInfo
    },
    {
      key: 'application_notarization',
      name: '申请公证',
      bgColor: '#D8E4FF',
      color: '#165DFF',
      method: () => handleNotarizationLink('application')
    },
    {
      key: 'cancel_notarization',
      name: '取消公证',
      bgColor: '#FFF7E8',
      color: '#FF7D00',
      method: handleCancelNotarization
    },
    {
      key: 'query_notarization',
      name: '查询公证结果',
      bgColor: '#E8FFEA',
      color: '#00B42A',
      method: handleQueryNotarization
    },
    {
      key: 'update_notarization_link',
      name: '更新公证链接',
      bgColor: '#D8E4FF',
      color: '#165DFF',
      method: () => handleNotarizationLink('update')
    },
    {
      key: 'update_id_card',
      name: '更新身份信息',
      bgColor: '#FFF7E8',
      color: '#FF7D00',
      method: () => handleUpdateIdCard()
    },
    {
      key: 'query_notarization_count',
      name: '查看已出证数量',
      bgColor: '#E8FFEA',
      color: '#00B42A',
      method: () => handleQueryNotarizationCount()
    }
  ]

  return (
    <>
      {notarizationBtnList.map(item => {
        return (
          <Button
            key={item.key}
            style={{
              background: item.bgColor,
              color: item.color,
              border: `1px solid ${item.color}`,
              marginLeft: '10px'
            }}
            loading={item.loading}
            onClick={() => item.method(item)}
          >
            {item.name}
          </Button>
        )
      })}
    </>
  )
}

export default Notarization
